// content.js
var app = getApp()
Page({

  /**
   * 页面的初始数据
   */
  data: {
    book: {},
    chapter: {},
    scrollTop: 0,
    preScrollTop:0,
    total: 0,
    actionSheetHidden: true,
    fontSize: 12
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    let book = app.data.currentBook
    this.setData({
      book,
      total: app.getChapters(book.id).length,
      fontSize:app.data.fontSize,
      scrollTop: Number(book.scrollTop)
    })
  },
  // 从目录回调显示
  onShow: function () {
    this.getContent(app.data.currentBook.currentChapter)
  },
  getContent(currentChapter,cType) {
    let param = { bookId: this.data.book.id, contentId: currentChapter }
    if(cType != null && cType != ""){
      param.type = cType
    }
    app.getRes(`detail`, param).then((data) => {
      app.data.currentBook.currentChapter = data.id
      this.data.book.currentChapter = data.id
      this.setData({
        chapter: data,
        book: this.data.book,
        scrollTop: 0
      })
    })
  },
  getNext (e) {
    this.getContent(e.currentTarget.dataset.currentchapter,"next")
    this.setData({
      scrollTop: 0
    });
  },
  getPre (e) {
    this.getContent(e.currentTarget.dataset.currentchapter,"pre")
    this.setData({
      scrollTop: 0
    });
  },
  toDirectory(e) {
    wx.navigateTo({
      url: `directory?bookid=${this.data.book.id}&title=${this.data.book.chapterName}&currentChapter=${this.data.book.currentChapter}`
    })
  },

  //点击文字触发的方法
  changeFont:function(){
    this.setData({
      actionSheetHidden: !this.data.actionSheetHidden
    });
  },
  
  //滑块互动之后触发的方法
  slider2change:function(e){
    app.setFont(e.detail.value);
    this.setData({
      fontSize: e.detail.value
    })
  },

  //点击取消的方法
  listenerActionSheet: function () {
    this.setData({
      actionSheetHidden: !this.data.actionSheetHidden
    })
  },

  onPageScroll(e) { // 获取滚动条当前位置
    this.setData({
      preScrollTop: e.detail.scrollTop
    })
  },
  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {
    if (app.data.bookcase[this.data.book.id]) {
      app.data.bookcase[this.data.book.id].currentChapter = this.data.book.currentChapter
      app.data.bookcase[this.data.book.id].scrollTop = this.data.preScrollTop
      wx.setStorageSync('bookcase', app.data.bookcase)
    }
  },
})